<template>
  <el-dialog
    v-model="visible"
    :title="`新增计划 - ${asset?.name || '-'}`"
    width="720px"
    :close-on-click-modal="false"
    :close-on-press-escape="false"
    class="plan-dialog"
  >
    <el-form ref="formRef" :model="form" :rules="rules" label-width="96px">
      <el-form-item label="设备">
        <el-input :model-value="asset?.name || '-'" disabled />
      </el-form-item>

      <el-form-item label="标题" prop="title">
        <el-input v-model="form.title" maxlength="80" show-word-limit placeholder="请输入计划标题"/>
      </el-form-item>

      <el-form-item label="计划日期" prop="planDate">
        <el-date-picker v-model="form.planDate" type="date" value-format="YYYY-MM-DD" style="width:100%"/>
      </el-form-item>
      <el-form-item label="状态" prop="status">
        <el-select v-model="form.status" placeholder="选择状态" style="width: 100%">
          <el-option label="已创建" value="GENERATED" />
          <el-option label="待执行" value="OPEN" />          
          <el-option label="已取消" value="CANCELLED" />
          <el-option label="已完成" value="DONE" />
        </el-select>
      </el-form-item>

      <el-form-item class="span-2" label="计划内容">
        <el-input v-model="form.planContent" type="textarea" rows="3" maxlength="500" show-word-limit placeholder="简要说明计划内容"/>
      </el-form-item>

      <el-form-item label="需备件">
        <el-switch v-model="form.needSpare" :active-value="1" :inactive-value="0"/>
      </el-form-item>

      <template v-if="form.needSpare === 1">
        <!-- 多选备件 -->
        <el-form-item label="选择备件">
          <el-select
            v-model="pickedIds"
            multiple
            filterable
            collapse-tags
            collapse-tags-tooltip
            placeholder="选择需要的备件（可多选）"
            style="width: 100%"
            @change="syncPickedToSpares"
          >
            <el-option
              v-for="op in spareOptions"
              :key="op.value"
              :label="op.label"
              :value="op.value"
            />
          </el-select>
        </el-form-item>

        <!-- 已选备件 + 数量编辑 -->
        <el-form-item label="备件清单">
          <el-table
            :data="form.spares"
            border
            size="small"
            style="width: 100%"
            empty-text="请在上方选择备件"
          >
            <el-table-column label="备件" min-width="220">
              <template #default="{ row }">
                {{ id2name(row.spareId) || row.spareId }}
              </template>
            </el-table-column>
            <el-table-column label="数量" width="140" align="center">
              <template #default="{ row }">
                <el-input-number
                  v-model="row.qty"
                  :min="1"
                  :max="9999"
                  :step="1"
                  controls-position="right"
                />
              </template>
            </el-table-column>
            <el-table-column label="操作" width="100" align="center">
              <template #default="{ row }">
                <el-button link type="danger" size="small" @click="removeSpare(row.spareId)">移除</el-button>
              </template>
            </el-table-column>
          </el-table>
        </el-form-item>
      </template>
    </el-form>

    <template #footer>
      <div style="display:flex; justify-content:flex-end; gap:8px">
        <el-button @click="visible=false">取消</el-button>
        <el-button type="primary" :loading="submitting" @click="submit">保存</el-button>
      </div>
    </template>
  </el-dialog>
</template>

<script setup>
import { ref, reactive, watch, onMounted } from 'vue'
import { createPlan } from '@/api/sbtz/mtplan'
import { listSpare } from '@/api/sbtz/spare' 
import { ElMessage } from 'element-plus'

const props = defineProps({
  modelValue: { type: Boolean, default: false },
  asset: { type: Object, default: () => ({}) }
})
const emit = defineEmits(['update:modelValue', 'success'])

const visible = ref(false)
watch(() => props.modelValue, v => (visible.value = v), { immediate: true })
watch(visible, v => emit('update:modelValue', v))

const formRef = ref()
const form = reactive({
  assetId: null,
  title: '',
  planDate: '',
  planContent: '',
  needSpare: 0,
  status: 'GENERATED',
  spares: []          // [{ spareId, qty }]
})

// 仅对标题/日期必填校验；spares 数量由业务自行保证
const rules = {
  title:    [{ required: true, message: '请输入标题', trigger: 'blur' }],
  planDate: [{ required: true, message: '请选择计划日期', trigger: 'change' }]
}

const spareOptions = ref([])       // [{value,label}]
const idNameMap = ref(new Map())   // spareId -> name
const pickedIds = ref([])          // 仅用于多选框

function id2name(id){ return idNameMap.value.get(id) }

async function loadSpares(){
  const res = await listSpare({ pageNum:1, pageSize:9999 })
  const rows = res?.rows ?? res?.data?.rows ?? res?.data ?? []
  spareOptions.value = rows.map(r => ({ value: r.id, label: r.name }))
  idNameMap.value = new Map(spareOptions.value.map(x => [x.value, x.label]))
}

// 多选值同步到 spares 数组（默认 qty=1）
function syncPickedToSpares() {
  const set = new Set(pickedIds.value)
  // 先保留仍在 set 里的项
  form.spares = form.spares.filter(it => set.has(it.spareId))
  // 新增新增项
  for (const id of set) {
    if (!form.spares.some(it => it.spareId === id)) {
      form.spares.push({ spareId: id, qty: 1 })
    }
  }
}

function removeSpare(spareId){
  pickedIds.value = pickedIds.value.filter(id => id !== spareId)
  form.spares = form.spares.filter(it => it.spareId !== spareId)
}

watch(() => props.asset?.id, id => {
  form.assetId = id || null
  form.title = ''
  form.planDate = ''
  form.planContent = ''
  form.needSpare = 0
  form.spares = []
  form.status = 'OPEN' // 重置
  pickedIds.value = []
})

onMounted(loadSpares)

const submitting = ref(false)
async function submit(){
  await formRef.value?.validate()
  console.log(form);
  console.log(props);
  // needSpare=1 且 spares 非空才合法（按需）
  if (form.needSpare === 1 && form.spares.length === 0) {
    return ElMessage.warning('请选择至少一个备件')
  }

  submitting.value = true
  try {
    const payload = {
      assetId: props.asset?.id ?? form.assetId,
      title: form.title,
      planDate: form.planDate,
      planContent: form.planContent,
      needSpare: form.needSpare,
      status: form.status,              // 新增
      spares: form.spares.map(x => ({ spareId: x.spareId, qty: x.qty, assetId: props.asset?.id ?? form.assetId }))
    }
    await createPlan(payload)
    visible.value = false
    emit('success')
  } finally {
    submitting.value = false
  }
}
</script>
